﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Data;
using Ccit.ClassLibrary;
using Ccit.SysPlat.Organ;
using Ccit.SysPlat.Log;
using Ccit.SysPlat.Purview;

namespace Ccit.Utils
{
    /// <summary>
    /// Description: 系统操作类
    /// Author: tim 2010-01-01
    /// </summary>
    public class SysInterface
    {
        #region init error log interface
        private static ILog _logInterface = Factory.CreateObject(MsErrLog.assemblyName, MsErrLog.className,
                                                    ImportComponentType.DotNetDll, null) as ILog;
        private const string _funcPageName = "通用系统接口";

        private static string _dbType = HttpContext.Current.Application["DBType"].ToString();
        #endregion

        #region public static interface

        /// <summary>
        /// 根据Id串获取获取名称串
        /// </summary>
        /// <param name="sIdstr">逗号分割的Id</param>
        /// <param name="enNameType">类型枚举</param>
        /// <param name="enSep">返回的名称之间的分隔符</param>
        /// <returns></returns>
        public static string GetNameStrByIdStr(string sIdstr, eSysRangeType enNameType, eSeparator enSep)
        {
            if (string.IsNullOrEmpty(sIdstr)) return string.Empty;
            string sRetValue = string.Empty;
            string separator = getSeparator(enSep);
            switch (enNameType)
            {
                case eSysRangeType.ORGAN:
                    IOrgan _organProcessor = Factory.CreateObject(MsOrgan.assemblyName, MsOrgan.className, ImportComponentType.DotNetDll, null) as IOrgan;
                    sRetValue = _organProcessor.GetOrganNamesByIds(sIdstr, separator);
                    _organProcessor = null;
                    break;
                case eSysRangeType.DEPT:
                    IDept _deptProcessor = Factory.CreateObject(MsDept.assemblyName, MsDept.className, ImportComponentType.DotNetDll, null) as IDept;
                    sRetValue = _deptProcessor.GetDeptNamesByIds(sIdstr, separator);
                    _deptProcessor = null;                    
                    break;
                case eSysRangeType.POS:
                    IPos _posProcessor = Factory.CreateObject(MsPos.assemblyName, MsPos.className, ImportComponentType.DotNetDll, null) as IPos;
                    sRetValue = _posProcessor.GetPosNamesByIds(sIdstr, separator);
                    _posProcessor = null;    
                    break;
                case eSysRangeType.CLS:
                    IClass _clsProcessor = Factory.CreateObject(MsClass.assemblyName, MsClass.className, ImportComponentType.DotNetDll, null) as IClass;
                    sRetValue = _clsProcessor.GetClassNamesByIds(sIdstr, separator);
                    _clsProcessor = null;  
                    break;
                case eSysRangeType.USER:
                    IUser _userProcessor = Factory.CreateObject(MsUser.assemblyName, MsUser.className, ImportComponentType.DotNetDll, null) as IUser;
                    sRetValue = _userProcessor.GetUserNamesByIds(sIdstr, separator);
                    _userProcessor = null; 
                    break;
                case eSysRangeType.ALL:
                    sRetValue = "全部人员";
                    break;
            }
                    
            return sRetValue;
        }

        /// <summary>
        /// 根据Id串获取获取名称串
        /// </summary>
        /// <param name="sIdstr">逗号分割的Id</param>
        /// <param name="rangeType">范围类型标志</param>
        /// <param name="enSep">返回的名称之间的分隔符</param>
        /// <returns></returns>
        public static string GetNameStrByIdStr(string sIdstr, string rangeType, eSeparator enSep)
        {
            if (string.IsNullOrEmpty(rangeType.Trim()) || string.IsNullOrEmpty(sIdstr)) return string.Empty;            
            eSysRangeType enNameType = (eSysRangeType)Enum.Parse(typeof(eSysRangeType), rangeType);
            string sRetValue = GetNameStrByIdStr(sIdstr, enNameType, enSep);
            return sRetValue;
        }

        
        /// <summary>
        /// 根据Id串获取获取名称串
        /// </summary>
        /// <param name="sIdstr">逗号分割的Id</param>
        /// <param name="enNameType">范围类型枚举</param>
        /// <param name="enSep">返回的名称之间的分隔符</param>
        /// <param name="isFilter">是否过滤掉无效的Id</param>
        /// <returns></returns>
        public static string GetNameStrByIdStr(string sIdstr, eSysRangeType enNameType, eSeparator enSep, eTrueFalse isFilter)
        {
            if (string.IsNullOrEmpty(sIdstr)) return string.Empty;
            string sRetValue = string.Empty;
            string separator = getSeparator(enSep);
            switch (enNameType)
            {
                case eSysRangeType.ORGAN:
                    IOrgan _organProcessor = Factory.CreateObject(MsOrgan.assemblyName, MsOrgan.className, ImportComponentType.DotNetDll, null) as IOrgan;
                    sRetValue = _organProcessor.GetOrganNamesByIds(sIdstr, separator, isFilter);
                    _organProcessor = null;
                    break;
                case eSysRangeType.DEPT:
                    IDept _deptProcessor = Factory.CreateObject(MsDept.assemblyName, MsDept.className, ImportComponentType.DotNetDll, null) as IDept;
                    sRetValue = _deptProcessor.GetDeptNamesByIds(sIdstr, separator, isFilter);
                    _deptProcessor = null;
                    break;
                case eSysRangeType.POS:
                    IPos _posProcessor = Factory.CreateObject(MsPos.assemblyName, MsPos.className, ImportComponentType.DotNetDll, null) as IPos;
                    sRetValue = _posProcessor.GetPosNamesByIds(sIdstr, separator, isFilter);
                    _posProcessor = null;
                    break;
                case eSysRangeType.CLS:
                    IClass _clsProcessor = Factory.CreateObject(MsClass.assemblyName, MsClass.className, ImportComponentType.DotNetDll, null) as IClass;
                    sRetValue = _clsProcessor.GetClassNamesByIds(sIdstr, separator, isFilter);
                    _clsProcessor = null;
                    break;
                case eSysRangeType.USER:
                    IUser _userProcessor = Factory.CreateObject(MsUser.assemblyName, MsUser.className, ImportComponentType.DotNetDll, null) as IUser;
                    sRetValue = _userProcessor.GetUserNamesByIds(sIdstr, separator, isFilter);
                    _userProcessor = null;
                    break;
                case eSysRangeType.ALL:
                    sRetValue = "全部人员";
                    break;
            }

            return sRetValue;
        }


        /// <summary>
        /// 根据Id串获取获取名称串
        /// </summary>
        /// <param name="sTableName">表名</param>
        /// <param name="sIdField">ID字段名</param>
        /// <param name="sNameField">名称字段名</param>
        /// <param name="sIdStr">ID串(逗号分隔)</param>
        /// <param name="enSep">返回的名称之间的分隔符枚举</param>
        /// <param name="whereClause">过滤条件 (如: AND NEWS_A2_140='0')</param>
        /// <returns></returns>
        public static string GetNameStrByIdStr(string sTableName, string sIdField, string sNameField,
                                                            string sIdStr, eSeparator enSep,string whereClause)
        {
            if (string.IsNullOrEmpty(sTableName) || string.IsNullOrEmpty(sIdField) || 
                        string.IsNullOrEmpty(sNameField) || string.IsNullOrEmpty(sIdStr)) return string.Empty;

            string separator = getSeparator(enSep);
            string strNames = string.Empty;
            string cmdText = "SELECT " + sNameField + " AS SHOWNAME FROM " + sTableName + " WHERE " + sIdField + " IN (" + sIdStr + ") ";
            cmdText += whereClause;
            try {
                string strName = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        strName = iReader["SHOWNAME"].ToString();
                        strNames += (string.IsNullOrEmpty(strNames)) ? strName : separator + strName;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            return strNames;
        }
       
        /// <summary>
        /// 根据Id串获取获取名称串 (适用于多主键情况)
        /// </summary>
        /// <param name="sTableName">表名</param>
        /// <param name="keyFields">主键字段名数组</param>
        /// <param name="sNameField">名称字段名</param>
        /// <param name="lstIdVal">Id值集合</param>
        /// <param name="enSep">分隔符</param>
        /// <returns></returns>
        public static string GetNameStrByIdStr(string sTableName, List<string> keyFields, string sNameField, 
                                                                        List<string[]> lstIdVal, eSeparator enSep)
        {
            int keyCount = keyFields.Count();
            string cmdText = "SELECT " + sNameField + " AS NAMEVAL FROM " + sTableName + " WHERE 1=1 AND (";
            int index = 0;
            foreach (string[] itemVal in lstIdVal)
            {
                if (index != 0)
                    cmdText += " OR ";
                for (int i = 0; i < keyCount; i++)
                {
                    if(i == 0)
                        cmdText += "(" + keyFields[i] + "='" + itemVal[i] + "' ";
                    else if(i != (keyCount - 1))
                        cmdText += "AND " + keyFields[i] + "='" + itemVal[i] + "' ";
                    else
                        cmdText += "AND " + keyFields[i] + "='" + itemVal[i] + "')";
                }

                index++;
            }

            cmdText += ")";

            string separator = getSeparator(enSep);
            string strNames = string.Empty;
            try {
                string strName = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        strName = iReader["NAMEVAL"].ToString();
                        strNames += (string.IsNullOrEmpty(strNames)) ? strName : separator + strName;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return strNames;
        }

        private static string getSeparator(eSeparator enSep)
        {
            string separator = string.Empty;
            switch (enSep)
            {
                case eSeparator.COMMA:
                    separator = ",";
                    break;
                case eSeparator.SPACE:
                    separator = " ";
                    break;
                case eSeparator.ENTER:
                    separator = "\r\n";
                    break;
            }
            return separator;
        }

        /// <summary>
        /// 过滤出有效的范围Id
        /// (由于范围数据有可能被删除，因此再使用前需要过滤出有效的范围Id)
        /// </summary>
        /// <param name="enRangeType">范围类型</param>
        /// <param name="rangeIds">待过滤的范围Id串</param>
        /// <returns></returns>
        public static string FilterEffectIds(eSysRangeType enRangeType, string rangeIds)
        {
            if (string.IsNullOrEmpty(rangeIds)) return rangeIds;

            if(enRangeType == eSysRangeType.ALL) return rangeIds;

            string effectIds = string.Empty;
            string cmdText = string.Empty;
            switch (enRangeType)
            {
                case eSysRangeType.USER:
                    cmdText = "SELECT SYS_A1_10 AS KEYID FROM SYS_A1 WHERE SYS_A1_10 IN (" + rangeIds + ") AND SYS_A1_90='0'";
                    break;
                case eSysRangeType.DEPT:
                    cmdText = "SELECT SYS_A2_10 AS KEYID FROM SYS_A2 WHERE SYS_A2_10 IN (" + rangeIds + ") AND SYS_A2_70='0'";
                    break;
                case eSysRangeType.POS:
                    cmdText = "SELECT SYS_A3_10 AS KEYID FROM SYS_A3 WHERE SYS_A3_10 IN (" + rangeIds + ") AND SYS_A3_60='0'";
                    break;
                case eSysRangeType.CLS:
                    cmdText = "SELECT SYS_A5_10 AS KEYID FROM SYS_A5 WHERE SYS_A5_10 IN (" + rangeIds + ") AND SYS_A5_60='0'";
                    break;               
            }
            
            try {
                string effectId = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        effectId = iReader["KEYID"].ToString();
                        effectIds += (string.IsNullOrEmpty(effectIds)) ? effectId : "," + effectId;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return effectIds;
        }

        /// <summary>
        /// 根据范围类型和范围Ids，返回对应的人员Ids
        /// </summary>
        /// <param name="enRangeType">范围类型</param>
        /// <param name="rangeIds">范围Ids</param>
        /// <param name="organId">机构Id</param>
        /// <returns></returns>
        public static string GetUserIdsByRangeType(eSysRangeType enRangeType, string rangeIds, string organId)
        {
            if (string.IsNullOrEmpty(rangeIds) && !enRangeType.Equals(eSysRangeType.ALL)) return string.Empty;

            string cmdText = string.Empty;
            string retUserIds = string.Empty;
            switch (enRangeType)
            {
                case eSysRangeType.USER:
                        retUserIds = rangeIds;
                   break;
                case eSysRangeType.DEPT:
                        cmdText = "SELECT SYS_A1_10 AS USERID FROM SYS_A1 WHERE SYS_A1_10 IN (SELECT SYS_R1_10 FROM SYS_R1 WHERE SYS_R1_20 IN ( " + rangeIds +
                             ")) AND SYS_A1_90='0'";
                        break;
                case eSysRangeType.POS:
                        cmdText = "SELECT SYS_A1_10 AS USERID FROM SYS_A1 WHERE SYS_A1_10 IN (SELECT SYS_R2_10 FROM SYS_R2 WHERE SYS_R2_20 IN (" + rangeIds +
                             ")) AND SYS_A1_90='0'";
                        break;
                case eSysRangeType.CLS:
                        cmdText = "SELECT SYS_A1_10 AS USERID FROM SYS_A1 WHERE SYS_A1_10 IN (SELECT SYS_R8_10 FROM SYS_R8 WHERE SYS_R8_20 IN (" + rangeIds +
                              ")) AND SYS_A1_90='0'";
                        break;
                case eSysRangeType.ALL:
                            cmdText = "SELECT SYS_A1_10 AS USERID FROM SYS_A1 WHERE SYS_A1_10 IN (SELECT SYS_R3_10 FROM SYS_R3 WHERE SYS_R3_20=" + organId +
                                      ") AND SYS_A1_90='0'";
                            break;
            }

            if (enRangeType.Equals(eSysRangeType.DEPT) || enRangeType.Equals(eSysRangeType.POS) || enRangeType.Equals(eSysRangeType.CLS) ||
                            enRangeType.Equals(eSysRangeType.ALL))
            {
                try {
                    string userId = string.Empty;
                    using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                    {
                        while (iReader.Read())
                        {
                            userId = iReader["USERID"].ToString();
                            retUserIds += (string.IsNullOrEmpty(retUserIds)) ? userId : "," + userId;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MsErrLog msErrorLog = new MsErrLog
                    {
                        funcPageName = _funcPageName,
                        errMsg = ex.Message,
                        codeTrack = ex.StackTrace,
                        errClassCode = "001", //SQL 异常
                        paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                    };

                    _logInterface.WriteErrorLog(msErrorLog);
                    msErrorLog = null;
                }
            }

            return retUserIds;
        }

        #endregion

        /// <summary>
        /// 返回页面的数据范围条件SQL
        /// </summary>
        /// <param name="tableName">页面对应的数据表名称</param>
        /// <param name="tabId">页签Id</param>
        /// <returns></returns>
        public static string GetPageDataRangeSQL(string tableName, string tabId)
        {            

            string cmdText = string.Empty;
            #region 先判断是否设置了范围权限
            bool bRangeSet = isHasRangeSet(tabId);
            if (!bRangeSet) return " (1=1) ";

            #endregion

            MsLoginUser loginUser = HttpContext.Current.Session["LogUserInfo"] as MsLoginUser;

            IRole _roleProcessor = Factory.CreateObject(MsRole.assemblyName,MsRole.className,ImportComponentType.DotNetDll,null) as IRole;
            string roleIds = _roleProcessor.GetRoleIdsByUserId(loginUser.userId, loginUser.userType, loginUser.organId);

            if (string.IsNullOrEmpty(roleIds)) return " (1=1) ";

            #region 获取数据范围设置

            if (_dbType.Equals("4")) //ACCESS
            {
                cmdText = "SELECT PUR_R2_30 AS RANGESIGN,PUR_R2_40 AS CUSTRANGETYPE,PUR_R2_50 AS CUSTRANGE FROM PUR_R2 " +
                          "WHERE PUR_R2_20=" + tabId + " AND PUR_R2_10 IN (" + roleIds + ")";
            }
            else {
                cmdText = "SELECT PUR_R2_30 AS RANGESIGN,PUR_R2_40 AS CUSTRANGETYPE,PUR_R2_50 AS CUSTRANGE FROM PUR_R2 " +
                          "WHERE PUR_R2_20='" + tabId + "' AND PUR_R2_10 IN (" + roleIds + ")";
            }

            string whereClause = " (1=1) ";
            try {
                string rangeSign = string.Empty;
                string custRangeType = string.Empty;
                string custRangeIds = string.Empty;
                string qryCon = string.Empty;                
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        rangeSign = iReader["RANGESIGN"].ToString();
                        custRangeType = iReader["CUSTRANGETYPE"].ToString();
                        custRangeIds = iReader["CUSTRANGE"].ToString();
                        if (rangeSign.Equals("9") || (rangeSign.Equals("5") && custRangeType.Equals("9"))) return " (1=1) ";

                        whereClause += (!string.IsNullOrEmpty(whereClause)) ? " OR " : string.Empty;
                        if (!rangeSign.Equals("5"))
                        {
                            #region 非自定义范围
                            switch (rangeSign)
                            {
                                case "0": //本人
                                    if (_dbType.Equals("4"))
                                        qryCon = tableName + "." + tableName + "_9994=" + loginUser.userId;
                                    else
                                        qryCon = tableName + "." + tableName + "_9994='" + loginUser.userId + "'";
                                    whereClause += "(" + qryCon + ")";
                                    break;
                                case "1": //本部门
                                    if (string.IsNullOrEmpty(loginUser.deptId)) //如果当前登陆用户没有部门则不能返回任何数据
                                    {
                                        whereClause += tableName + "." + tableName + "_9991=NULL";
                                    }
                                    else
                                    {
                                        if (_dbType.Equals("4"))
                                        {
                                            qryCon = tableName + "." + tableName + "_9991=" + loginUser.deptId;
                                        }
                                        else
                                        {
                                            qryCon = tableName + "." + tableName + "_9991='" + loginUser.deptId + "'";
                                        }
                                    }
                                    whereClause += "(" + qryCon + ")";
                                    break;
                                case "2": //本职位
                                    if (string.IsNullOrEmpty(loginUser.posId))
                                    {
                                        whereClause += tableName + "." + tableName + "_9992=NULL";
                                    }
                                    else
                                    {
                                        if (_dbType.Equals("4"))
                                        {
                                            qryCon = tableName + "." + tableName + "_9992=" + loginUser.posId;
                                        }
                                        else
                                        {
                                            qryCon = tableName + "." + tableName + "_9992='" + loginUser.posId + "'";
                                        }
                                    }
                                    whereClause += "(" + qryCon + ")";
                                    break;
                                case "3": //本级别
                                    if (string.IsNullOrEmpty(loginUser.classId))
                                    {
                                        whereClause += tableName + "." + tableName + "_9993=NULL";
                                    }
                                    else
                                    {
                                        if (_dbType.Equals("4"))
                                        {
                                            qryCon = tableName + "." + tableName + "_9993=" + loginUser.classId;
                                        }
                                        else
                                        {
                                            qryCon = tableName + "." + tableName + "_9993='" + loginUser.classId + "'";
                                        }
                                    }
                                    whereClause += "(" + qryCon + ")";
                                    break;
                                case "8": //本机构                                   
                                    if (_dbType.Equals("4"))
                                    {
                                        qryCon = tableName + "." + tableName + "_9990=" + loginUser.organId;
                                    }
                                    else
                                    {
                                        qryCon = tableName + "." + tableName + "_9990='" + loginUser.organId + "'";
                                    }
                                    whereClause += "(" + qryCon + ")";
                                    break;
                            }
                            #endregion
                        }
                        else {
                            qryCon = tableName + "." + tableName;
                            switch (custRangeType)
                            {
                                case "0":   //按人员
                                    qryCon += "_9994";
                                    break;
                                case "1":   //按部门
                                    qryCon = "_9991";
                                    break;
                                case "2":   //按职位
                                    qryCon = "_9992";
                                    break;
                                case "3":   //按级别
                                    qryCon = "_9993";
                                    break;
                                case "4":   //按工作组
                                    qryCon = string.Empty;
                                    break;
                                case "5":   //按条件
                                    qryCon = string.Empty;
                                    break;
                                case "8":   //按机构
                                    qryCon = "_9990";
                                    break;
                            }

                            whereClause += "(" + qryCon + " IN (" + custRangeIds + "))";
                        }               
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            #endregion

            return whereClause;
        }

        private static bool isHasRangeSet(string menuId)
        {
            if (string.IsNullOrEmpty(menuId)) return false;

            string cmdText = string.Empty;
            if (_dbType.Equals("4")) //ACCESS
            {
                cmdText = "SELECT PUR_B1_120 AS RANGESET FROM PUR_B1 WHERE PUR_B1_10=" + menuId;
            }
            else cmdText = "SELECT PUR_B1_120 AS RANGESET FROM PUR_B1 WHERE PUR_B1_10='" + menuId + "'";

            try
            {
                string rangeSet = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    if (iReader.Read() && null != iReader[0])
                        rangeSet = iReader["RANGESET"].ToString();
                }

                return (rangeSet.Equals("1") ? true : false);
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return false;
            }
            
        }

        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="queryName">要查询的数据</param>
        /// <param name="enNameType">查询操作类型枚举</param>
        /// <param name="detailSign">是否显示详细标志</param>
        /// <param name="matchType">匹配类型</param>
        /// <returns></returns>
        public static string QueryDataXMLByName(string queryName, eSysRangeType enNameType,string detailSign,string matchType)
        {
            string sRetXML = "";
            MsLoginUser loginUser = (MsLoginUser)HttpContext.Current.Session["LogUserInfo"];
            string sQryName = queryName.Trim();

            switch (enNameType)
            {
                case eSysRangeType.ORGAN:
                    sRetXML = string.Empty;
                    break;
                case eSysRangeType.DEPT:
                    sRetXML = getDeptXMLByName(sQryName, matchType);
                    break;
                case eSysRangeType.POS:                   
                    sRetXML = getPosXMLByName(queryName, matchType);
                    break;
                case eSysRangeType.CLS:
                    sRetXML = getClsXMLByName(queryName, matchType);
                    break;
                case eSysRangeType.USER:
                    sRetXML = getUserXMLByName(queryName, matchType);
                    sRetXML = buildUserDetailXML(sRetXML, detailSign);
                    break;
            }
            return sRetXML;
        }

        private static string getDeptXMLByName(string queryName,string matchType)
        {
            string cmdText = string.Empty;
            if(string.IsNullOrEmpty(queryName))            
                cmdText = "SELECT SYS_A2_10 AS DEPTID,SYS_A2_20 AS DEPTNAME,SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_70='0' ORDER BY SYS_A2_30 ASC";
            else
                if(matchType == "0")
                    cmdText = "SELECT SYS_A2_10 AS DEPTID,SYS_A2_20 AS DEPTNAME,SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_70='0' AND SYS_A2_20 LIKE '%" +
                              queryName + "%' ORDER BY SYS_A2_30 ASC";
                else
                    cmdText = "SELECT SYS_A2_10 AS DEPTID,SYS_A2_20 AS DEPTNAME,SYS_A2_30 AS LAYCODE FROM SYS_A2 WHERE SYS_A2_70='0' AND SYS_A2_20 LIKE '" +
                              queryName + "%' ORDER BY SYS_A2_30 ASC";
               
            StringBuilder sbDept = new StringBuilder("<DEPTS>");
            try{
                string layCode = string.Empty;
                int bmLen = 0;
                string indPrefix = string.Empty; //缩进前缀
                using(IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while(iReader.Read())
                    {
                        if (!string.IsNullOrEmpty(queryName))
                        {
                            layCode = iReader["LAYCODE"].ToString();
                            bmLen = layCode.Length / 4;
                            indPrefix = string.Empty;
                            for (int j = 0; j < bmLen - 1; j++)
                            {
                                indPrefix += "\u3000";
                            }
                        }
                        else
                            indPrefix = string.Empty;

                        sbDept.Append("<DEPT><DEPTID>").Append(iReader["DEPTID"].ToString()).Append("</DEPTID><DEPTNAME><![CDATA[");
                        sbDept.Append(indPrefix + iReader["DEPTNAME"].ToString()).Append("]]></DEPTNAME></DEPT>");
                    }
                }
            }
            catch(Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbDept.Append("</DEPTS>");
            return sbDept.ToString();
        }

        private static string getPosXMLByName(string queryName,string matchType)
        {
            string cmdText = string.Empty;
            if(string.IsNullOrEmpty(queryName))            
                cmdText = "SELECT SYS_A3_10 AS POSID,SYS_A3_20 AS POSNAME FROM SYS_A3 WHERE SYS_A3_60='0' ORDER BY SYS_A3_50 ASC";
            else
                if(matchType == "0")
                    cmdText = "SELECT SYS_A3_10 AS POSID,SYS_A3_20 AS POSNAME FROM SYS_A3 WHERE SYS_A3_60='0' AND SYS_A3_20 LIKE '%" +
                              queryName + "%' ORDER BY SYS_A3_50 ASC";
                else
                    cmdText = "SELECT SYS_A3_10 AS POSID,SYS_A3_20 AS POSNAME FROM SYS_A3 WHERE SYS_A3_60='0' AND SYS_A3_20 LIKE '" +
                              queryName + "%' ORDER BY SYS_A3_50 ASC";
               
            StringBuilder sbPos = new StringBuilder("<POSES>");
            try{
                using(IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while(iReader.Read())
                    {
                        sbPos.Append("<POS><POSID>").Append(iReader["POSID"].ToString()).Append("</POSID><POSNAME><![CDATA[");
                        sbPos.Append(iReader["POSNAME"].ToString()).Append("]]></POSNAME></POS>");
                    }
                }
            }
            catch(Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbPos.Append("</POSES>");
            return sbPos.ToString();
        }

        private static string getClsXMLByName(string queryName, string matchType)
        {
            string cmdText = string.Empty;
            if(string.IsNullOrEmpty(queryName))            
                cmdText = "SELECT SYS_A5_10 AS CLASSID,SYS_A5_20 AS CLASSNAME FROM SYS_A5 WHERE SYS_A5_60='0' ORDER BY SYS_A5_50 ASC";
            else
                if(matchType == "0")
                    cmdText = "SELECT SYS_A5_10 AS CLASSID,SYS_A5_20 AS CLASSNAME FROM SYS_A5 WHERE SYS_A5_60='0' AND SYS_A5_20 LIKE '%" +
                              queryName + "%' ORDER BY SYS_A5_50 ASC";
                else
                    cmdText = "SELECT SYS_A5_10 AS CLASSID,SYS_A5_20 AS CLASSNAME FROM SYS_A5 WHERE SYS_A5_60='0' AND SYS_A5_20 LIKE '" +
                              queryName + "%' ORDER BY SYS_A5_50 ASC";
              
            StringBuilder sbCls = new StringBuilder("<CLASSES>");
            try{
                using(IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while(iReader.Read())
                    {
                        sbCls.Append("<CLASS><ID>").Append(iReader["CLASSID"].ToString()).Append("</ID><NAME><![CDATA[");
                        sbCls.Append(iReader["CLASSNAME"].ToString()).Append("]]></NAME></CLASS>");
                    }
                }
            }
            catch(Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCls.Append("</CLASSES>");
            return sbCls.ToString();
        }

        private static string getUserXMLByName(string queryName, string matchType)
        {
            string cmdText = string.Empty;

            if(string.IsNullOrEmpty(queryName))
                cmdText = "SELECT SYS_A1_10 AS USERID,SYS_A1_40 AS USERNAME FROM SYS_A1 WHERE SYS_A1_90='0' ORDER BY SYS_A1_80 ASC";
            else
                if(matchType == "0")
                    cmdText = "SELECT SYS_A1_10 AS USERID,SYS_A1_40 AS USERNAME FROM SYS_A1 WHERE SYS_A1_90='0' AND SYS_A1_40 LIKE '%" + queryName + "%'";
                else
                    cmdText = "SELECT SYS_A1_10 AS USERID,SYS_A1_40 AS USERNAME FROM SYS_A1 WHERE SYS_A1_90='0' AND SYS_A1_40 LIKE '" + queryName + "%'";
               
            StringBuilder sbUser = new StringBuilder("<USERS>");
            try{
                using(IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while(iReader.Read())
                    {
                        sbUser.Append("<USER><USERID>").Append(iReader["USERID"].ToString()).Append("</USERID><USERNAME><![CDATA[");
                        sbUser.Append(iReader["USERNAME"].ToString()).Append("]]></USERNAME></USER>");
                    }
                }
            }
            catch(Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbUser.Append("</USERS>");
            return sbUser.ToString();
        }

        private static string buildUserDetailXML(string strXML, string detailSign)
        {
            if (string.IsNullOrEmpty(strXML) || detailSign == "0") return strXML;

            XElement xeUser = XElement.Parse(strXML);
            IEnumerable<XElement> userQuery = from eUser in xeUser.Elements("USER")
                                              select eUser;

            StringBuilder sb = new StringBuilder("<USERS>");
            IUser _userProcessor = Factory.CreateObject(MsUser.assemblyName, MsUser.className, ImportComponentType.DotNetDll, null) as IUser;
            MsUser msUser = null;
            foreach (var eUser in userQuery)
            {
                msUser = _userProcessor.GetUserInfo(eUser.Element("USERID").Value,eTrueFalse.TRUE);
                sb.Append("<USER><USERID>").Append(eUser.Element("USERID").Value).Append("</USERID>");
                sb.Append("<USERNAME><![CDATA[").Append(eUser.Element("USERNAME").Value).Append("]]></USERNAME>");
                sb.Append("<ORGANNAME><![CDATA[").Append(msUser.belongOrgan.organName).Append("]]></ORGANNAME>");
                sb.Append("<DEPTNAME><![CDATA[").Append(msUser.belongDept.deptName).Append("]]></DEPTNAME>");
                sb.Append("<POSNAME><![CDATA[").Append(msUser.belongPos.posName).Append("]]></POSNAME>");
                sb.Append("<CLASSNAME><![CDATA[").Append(msUser.belongClass.clsName).Append("]]></CLASSNAME>");
                sb.Append("</USER>");
                msUser = null;
            }

            sb.Append("</USERS>");

            _userProcessor = null;
            xeUser = null;
            return sb.ToString();
        }

        /// <summary>
        /// 获取人员范围类型的描述信息
        /// </summary>
        /// <param name="rangeType">
        /// 0：按人员：1：按部门；2：按职位；3：按级别；4：按工作组：5：按条件；8：按机构；9：全部人员：
        /// </param>
        /// <returns></returns>
        public static string GetRangeTypeDesc(string rangeType)
        {
            string rangeTypeDesc = "";
            switch (rangeType)
            {
                case "0":
                    rangeTypeDesc = "按人员";
                    break;
                case "1":
                    rangeTypeDesc = "按部门";
                    break;
                case "2":
                    rangeTypeDesc = "按职位";
                    break;
                case "3":
                    rangeTypeDesc = "按级别";
                    break;
                case "4":
                    rangeTypeDesc = "按工作组";
                    break;
                case "5":
                    rangeTypeDesc = "按条件";
                    break;
                case "6":
                    rangeTypeDesc = "按机构";
                    break;
                case "7":
                    rangeTypeDesc = "全部人员";
                    break;
            }

            return rangeTypeDesc;
        }
                
    }

}
